﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Channels;
using PreluareDateDePeEBay.eBayService;
using Excel = Microsoft.Office.Interop.Excel;
using System.Data;
using System.Threading;
using System.IO;
using System.Runtime.InteropServices;
using System.Data.SqlClient;
  
namespace PreluareDateDePeEBay
{    
    class Program
    {
        static String[] categoriiBaza = { "books" , "multimedia", "games", "movies", "electronics", "laptops", "cameras", "ebooks" };

        static Dictionary<string, int> dictionarCategorii = new Dictionary<string, int> {
                {"Books", 4 },
                { "DVDs & Movies", 8},
                { "Cameras & Photo", 11},
                { "Cell Phones & PDAs", 9},
                { "Computers & Networking", 9}
        };

        static DataTable dataTableCategorii;

        static String CategoriiAcceptate = "Cell Phones & PDAs"; //"Books Cameras & Photo Cell Phones & PDAs Computers & Networking DVDs & Movies ";  

        static void citesteEXCEL()
        { 
            Excel.Application xlApp = new Excel.Application();
            Excel.Workbook xlWorkbook = xlApp.Workbooks.Add(1);
            xlWorkbook = xlApp.Workbooks.Open(System.IO.Path.GetFullPath("subcategorii.xls"),Type.Missing,Type.Missing);
            Excel.Worksheet Sheet = (Excel.Worksheet)xlWorkbook.Sheets.get_Item(1);

            Excel.Range SheetRange;
             
            SheetRange = Sheet.UsedRange; //gives the used cells in sheet
               
            //Reading Excel file.
            //Creating datatable to read the containt of the Sheet in File.
            dataTableCategorii = new DataTable();

            dataTableCategorii.Columns.Add("Subcategory ID");
            dataTableCategorii.Columns.Add("Category");
            dataTableCategorii.Columns.Add("Subcategory");

            int Cnum = 0;
            int Rnum = 0;

            for (Rnum = 2; Rnum <= SheetRange.Rows.Count; Rnum++)
                {
                    DataRow dr = dataTableCategorii.NewRow();
                    //Reading Each Column value From sheet to datatable Colunms     
              

                    for (Cnum = 1; Cnum <= SheetRange.Columns.Count; Cnum++)
                    {
                        dr[Cnum - 1] = (SheetRange.Cells[Rnum, Cnum] as Excel.Range).Value2.ToString();
                    }
                    
                    // Adaug randul numai daca imi convine categoria
                    if (CategoriiAcceptate.LastIndexOf(dr[1].ToString()) >= 0)
                    {
                        dataTableCategorii.Rows.Add(dr); // adding Row into DataTable
                        dataTableCategorii.AcceptChanges();
                    }
                }

            GC.Collect();
            GC.WaitForPendingFinalizers();

            Marshal.FinalReleaseComObject(SheetRange);
            Marshal.FinalReleaseComObject(Sheet);

            xlWorkbook.Close(Type.Missing, Type.Missing, Type.Missing);
            Marshal.FinalReleaseComObject(xlWorkbook);

            xlApp.Quit();
            Marshal.FinalReleaseComObject(xlApp);

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();    
        }

        static void pornesteThreaduri()
        {
            for (int i = 0; i < dataTableCategorii.Rows.Count; i++)
            {
                Thread newThread = new Thread(Program.preiaDateDePeEBay);
                newThread.Start(dataTableCategorii.Rows[i]);                
            }
        }

        public enum TipRequest { KeyWords, Categorie, Product }
        static void Main(string[] args)
        {
            citesteEXCEL();
            pornesteThreaduri();
            // preiaDateDePeEBay(dataTableCategorii.Rows[5]);
            //modificaDateDupaProductID("ISBN", "0691017794");         
        }

        static int NumarErori=0;
        static public void preiaDateDePeEBay(object subCategorie) // Ii trimit dataRow-ul
        {  
            DataRow dataRow = (DataRow)subCategorie;


            DateTime dt1 = DateTime.Now;                  

            // deschid un writer pentru a scrie in fisier.
            TextWriter tw = new StreamWriter("Rezultat\\" + dataRow["Category"].ToString() +" "+ dataRow["Subcategory"].ToString() + ".txt");

            int numarEroriNull = 1;
            TextWriter twErrNull = new StreamWriter("Erori\\EX " + dataRow["Category"].ToString() + " " + dataRow["Subcategory"].ToString() + ".txt");            
            
            var tip = TipRequest.Categorie;
            
            using (FindingServicePortTypeClient client = new FindingServicePortTypeClient())
            {
                MessageHeader header = MessageHeader.CreateHeader("CustomHeader", "", "");
                using (OperationContextScope scope = new OperationContextScope(client.InnerChannel))
                {

                    OperationContext.Current.OutgoingMessageHeaders.Add(header);

                    HttpRequestMessageProperty httpRequestProperty = new HttpRequestMessageProperty();

                    httpRequestProperty.Headers.Add("X-EBAY-SOA-SECURITY-APPNAME", "FilipSin-b22f-4d3d-90c6-68eb75bf2db2");  // Acest ultim argument l-am luat de pe contul de eBay Developer de la Application Settings
                    
                    httpRequestProperty.Headers.Add("X-EBAY-SOA-OPERATION-NAME", "findItemsByCategory"); 
                    
                    httpRequestProperty.Headers.Add("X-EBAY-SOA-GLOBAL-ID", "EBAY-US");

                    OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;

                   
                    try
                                {
                                    int NumarPagina = 10;
                                    for (; ; )
                                    {
                                        FindItemsByCategoryRequest req = new FindItemsByCategoryRequest() { categoryId = new string[] { dataRow["Subcategory ID"].ToString() } };
                                        
                                        // Filtru pentru a cauta doar produsele noi
                                        ItemFilter filtru = new ItemFilter();
                                        filtru.name = ItemFilterType.Condition;
                                        filtru.value = new string[1];
                                        filtru.value[0] = "New";

                                        // Adaugarea acestui filtru  obiectului request
                                        req.itemFilter = new ItemFilter[1];
                                        req.itemFilter[0] = filtru;

                                        PaginationInput pi = new PaginationInput();
                                        pi.entriesPerPage = 200;
                                        pi.entriesPerPageSpecified = true;
                                        pi.pageNumberSpecified = true;
                                        pi.pageNumber = NumarPagina;
                                        NumarPagina++;

                                        req.paginationInput = pi;

                                        FindItemsByCategoryResponse res = client.findItemsByCategory(req);

                                        DateTime dt11 = DateTime.Now; 

                                        foreach (var v in res.searchResult.item)
                                        { // Am vazut ca imi da exceptie pentru campurile in care v are atribute null                                            
                                            String title = "", pret = "", itemId = "", galleryUrl = "", location = "", postalCode = "", condition = "", url="";
                                            try
                                            {
                                                if (v.title != null) title = v.title;
                                                pret = v.sellingStatus.currentPrice.Value.ToString();
                                                if (v.itemId != null) itemId = v.itemId;
                                                if (v.galleryURL != null) galleryUrl = v.galleryURL;
                                                if (v.postalCode != null) postalCode = v.postalCode;
                                                if (v.condition.conditionDisplayName != null) condition = v.condition.conditionDisplayName;
                                                if (v.viewItemURL != null) url = v.viewItemURL;
                                                
                                            }
                                            catch (Exception e)
                                            {
                                                twErrNull.WriteLine(numarEroriNull + "     " + e.Message+" \n");
                                                numarEroriNull++;
                                            }

                                            Database1 db = new Database1();
                                            DateTime dt2 = DateTime.Now; 
                                           
                                            ParsareSursa parsing = new ParsareSursa();

                                            DateTime dt3;

                                            if (url != "")
                                            {
                                                if (dataRow["Category"].ToString().Equals("Books"))
                                                {
                                                    //voi cauta mai intai ISBN
                                                    String ISBN = parsing.Gaseste(url, 1);
                                                    dt3 = DateTime.Now; 
                                                    if (ISBN != "" && ISBN != null)
                                                    {
                                                        /*
                                                        tw.WriteLine(title + "          Pretul " + pret + "       itemID:" + itemId +
                                                          "     Imagine: " + galleryUrl + "    Locatie: " + location + "     cod Postal " + postalCode +
                                                          "    Conditia " + condition + "     URL: " + url + "  ISBN: " + ISBN);
                                                        */

                                                        int categ_id = dictionarCategorii[dataRow["Category"].ToString()];
                                                        db.insertProduct(title, "", condition, "", galleryUrl, "", "", "", ISBN, categ_id, "", pret, url);
                                                    }
                                                    else
                                                    {
                                                        String UPC = parsing.Gaseste(url, 2);

                                                        if (UPC != "" && UPC != null)
                                                        {
                                                            /*
                                                            tw.WriteLine(title + "          Pretul " + pret + "       itemID:" + itemId +
                                                              "     Imagine: " + galleryUrl + "    Locatie: " + location + "     cod Postal " + postalCode +
                                                              "    Conditia " + condition + "     URL: " + url + "  UPC: " + UPC);
                                                            */

                                                            int categ_id = dictionarCategorii[dataRow["Category"].ToString()];
                                                            db.insertProduct(title, "", condition, "", galleryUrl, "", "", UPC, "", categ_id, "", pret, url);
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    String UPC = parsing.Gaseste(url, 2);
                                                    dt3 = DateTime.Now; 
                                                    if (UPC != "" && UPC != null)
                                                    {
                                                        /*
                                                        tw.WriteLine(title + "          Pretul " + pret + "       itemID:" + itemId +
                                                          "     Imagine: " + galleryUrl + "    Locatie: " + location + "     cod Postal " + postalCode +
                                                          "    Conditia " + condition + "     URL: " + url + "  UPC: " + UPC);
                                                        */

                                                        int categ_id = dictionarCategorii[dataRow["Category"].ToString()];
                                                        db.insertProduct(title, "", condition, "", galleryUrl, "", "", UPC, "", categ_id, "", pret, url);
                                                    }
                                                }
                                            }
                                            DateTime dt4 = DateTime.Now; 
                                        }
  
                                    }
                                }
                                catch (Exception e)
                                {
                                    TextWriter twErr = new StreamWriter("Erori\\E " + dataRow["Category"].ToString() + " " + dataRow["Subcategory"].ToString() + ".txt");
                                    twErr.WriteLine(e.Message);                                    
                                    twErr.Close();
                                }                    

                    //Console.Read();
                }
            }        

            tw.Close();
            twErrNull.Close();
        }

        static public void modificaDateDupaProductID(string type, string Value) // Ii trimit dataRow-ul
        {
            using (FindingServicePortTypeClient client = new FindingServicePortTypeClient())
            {
                MessageHeader header = MessageHeader.CreateHeader("CustomHeader", "", "");
                using (OperationContextScope scope = new OperationContextScope(client.InnerChannel))
                {

                    OperationContext.Current.OutgoingMessageHeaders.Add(header);

                    HttpRequestMessageProperty httpRequestProperty = new HttpRequestMessageProperty();

                    httpRequestProperty.Headers.Add("X-EBAY-SOA-SECURITY-APPNAME", "FilipSin-b22f-4d3d-90c6-68eb75bf2db2");  // Acest ultim argument l-am luat de pe contul de eBay Developer de la Application Settings
                    
                    httpRequestProperty.Headers.Add("X-EBAY-SOA-OPERATION-NAME", "findItemsByProduct"); 
                    
                    httpRequestProperty.Headers.Add("X-EBAY-SOA-GLOBAL-ID", "EBAY-US");

                    OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;

                    FindItemsByProductRequest request = new FindItemsByProductRequest();
                    request.productId = new ProductId();
                    request.productId.type = type;
                    request.productId.Value = Value;
                    
                    ItemFilter filtru = new ItemFilter();
                    filtru.name = ItemFilterType.Condition;
                    filtru.value = new string[1];
                    filtru.value[0] = "New";

                    request.itemFilter = new ItemFilter[1];
                    request.itemFilter[0] = filtru;

                    FindItemsByProductResponse response = client.findItemsByProduct(request);

                    foreach (var item in response.searchResult.item)
                    {
                        Console.WriteLine(item.title + "%%%" + item.sellingStatus.currentPrice.Value+"   "+item.condition.conditionDisplayName);
                    }
                 }                 
            }
        }
    }
}